<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useMenuApi } from '@/api/menu/index'

// 状态管理
const menuApi = useMenuApi()
const menuTreeRef = ref()
const menuFormRef = ref()
const state = reactive({
  loading: false,
  pageIndex: 1,
  pageSize: 6,
  data: [],
  searchParams: {
    name: '',
    status: undefined
  },
  showEdit: false,
  dialogTitle: '',
  menuForm: {
    id: undefined,
    parentId: 0,
    name: '',
    type: 1,
    icon: '',
    path: '',
    redirect: '',
    hidden: 0,
    permission: '',
    sort: 0,
    status: 0,
    description: ''
  },
  menuRules: {
    name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
    path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
    component: [{ required: true, message: '组件路径不能为空', trigger: 'blur' }],
    permission: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
  }
})

// 获取表格数据
const getTableData = async () => {
  try {
    state.loading = true
    state.data = await menuApi.getList(state.searchParams)
  } finally {
    state.loading = false
  }
}

// 重置查询
const resetSearch = () => {
  state.searchParams = {}
  getTableData()
}

// 展开/折叠行
const handleExpand = (bool) => {
  if (menuTreeRef.value) {
    const allRows = getAllRows(state.data)
    allRows.forEach((row) => {
      menuTreeRef.value.toggleRowExpansion(row, bool)
    })
  }
}

// 获取所有行（包括子行）
const getAllRows = (rows) => {
  let allRows = []
  rows.forEach((row) => {
    allRows.push(row)
    if (row.children && row.children.length > 0) {
      allRows = allRows.concat(getAllRows(row.children))
    }
  })
  return allRows
}

// 打开弹窗
const openEdit = (row, isEdit) => {
  state.showEdit = true
  state.dialogTitle = '添加菜单'
  state.menuForm.sort = state.data.length + 2
  if (row) {
    if (isEdit) {
      state.dialogTitle = '修改菜单'
      state.menuForm = { ...row }
    } else {
      state.menuForm.parentId = row.id
      state.menuForm.type = 2
      state.menuForm.sort = row.children.length + 2
    }
  }
}

// 处理关闭
const handleClose = () => {
  menuFormRef.value.resetFields()
}

// 处理提交
const handleSubmit = async () => {
  menuFormRef.value.validate(async (valid) => {
    if (valid) {
      if (state.menuForm.id) {
        await menuApi.update(state.menuForm)
      } else {
        await menuApi.save(state.menuForm)
      }
      state.showEdit = false
      ElMessage.success('操作成功')
      await getTableData()
    }
  })
}

// 处理删除
const handleRemove = (ids) => {
  ElMessageBox.confirm('确认要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await menuApi.remove(ids)
    ElMessage.success('删除成功')
    await getTableData()
  })
}

// 初始化加载菜单
onMounted(() => {
  getTableData()
})

const options = [
  {
    value: 'Option1',
    label: 'Option1'
  },
  {
    value: 'Option2',
    label: 'Option2'
  },
  {
    value: 'Option3',
    label: 'Option3'
  },
  {
    value: 'Option4',
    label: 'Option4'
  },
  {
    value: 'Option5',
    label: 'Option5'
  }
]
</script>

<template>
  <el-card>
    <el-form :model="state.searchParams" :inline="true">
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="state.searchParams.name" placeholder="请输入菜单名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="菜单状态" prop="status">
            <el-select v-model="state.searchParams.status" clearable placeholder="请选择菜单状态" style="width: 190px">
              <el-option :value="0" label="启用" />
              <el-option :value="1" label="禁用" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item>
            <el-button type="primary" icon="search" @click="getTableData"> 搜索 </el-button>
            <el-button icon="refresh" @click="resetSearch"> 清空 </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <el-button v-auth="'menu:save'" type="primary" icon="plus" @click="openEdit(null)">创建菜单</el-button>
      <el-button type="primary" icon="ArrowDown" @click="handleExpand(true)">全部展开</el-button>
      <el-button type="primary" icon="ArrowUp" @click="handleExpand(false)">全部折叠</el-button>
    </el-row>

    <el-table
      class="mt10"
      ref="menuTreeRef"
      row-key="id"
      :loading="state.loading"
      element-loading-text="正在努力加载数据中..."
      :data="state.data"
      border
      stripe
    >
      <el-table-column prop="name" label="菜单名称" min-width="180" show-overflow-tooltip />
      <el-table-column prop="icon" label="菜单图标" min-width="100">
        <template #default="{ row }">
          <el-button :icon="row.icon" bg text></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="菜单类型" min-width="100">
        <template #default="{ row }">
          <el-tag type="primary" v-if="row.type === 1" effect="plain">目录</el-tag>
          <el-tag type="success" v-if="row.type === 2" effect="plain">菜单</el-tag>
          <el-tag type="info" v-if="row.type === 3" effect="plain">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="优先级" min-width="100" sortable />
      <el-table-column prop="path" label="菜单路径" min-width="150" show-overflow-tooltip />
      <el-table-column prop="permission" label="权限标识" min-width="120" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" min-width="120">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.status === 0" effect="plain">正常</el-tag>
          <el-tag type="danger" v-if="row.status === 1" effect="plain">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="120" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" min-width="120" sortable show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-link v-auth="'menu:save'" type="primary" icon="plus" @click="openEdit(row, false)">添加 </el-link>
          <el-divider v-auth="'menu:update'" direction="vertical" />
          <el-link v-auth="'menu:update'" type="success" icon="edit" @click="openEdit(row, true)">编辑 </el-link>
          <el-divider v-auth="'menu:delete'" direction="vertical" />
          <el-link v-auth="'menu:delete'" type="danger" icon="remove" @click="handleRemove([row.id])">删除 </el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="state.showEdit" :title="state.dialogTitle" @close="handleClose">
      <el-form ref="menuFormRef" :model="state.menuForm" :rules="state.menuRules" label-width="100px">
        <el-row>
          <el-col v-if="state.menuForm.parentId != 0 || state.menuForm.id" :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="上级菜单" prop="parentId">
              <el-tree-select
                v-model="state.menuForm.parentId"
                placeholder="请选择上级菜单"
                :data="state.data"
                :props="{ value: 'id', label: 'name' }"
                check-strictly
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="state.menuForm.name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="state.menuForm.type">
                <el-radio-button :value="1">目录</el-radio-button>
                <el-radio-button :value="2">菜单</el-radio-button>
                <el-radio-button :value="3">按钮</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="菜单图标" prop="icon">
              <el-input v-model="state.menuForm.icon" placeholder="请输入菜单图标" />
            </el-form-item>
          </el-col>
          <el-col v-if="state.menuForm.type != 3" :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="路由地址" prop="path">
              <el-input v-model="state.menuForm.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col v-if="state.menuForm.type == 1" :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="重定向" prop="redirect">
              <el-input v-model="state.menuForm.redirect" placeholder="请输入重定向路由" />
            </el-form-item>
          </el-col>
          <el-col v-if="state.menuForm.type == 2" :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="state.menuForm.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col v-if="state.menuForm.type != 1" :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="权限标识" prop="permission">
              <el-input v-model="state.menuForm.permission" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="优先级" prop="priority">
              <el-input-number
                v-model="state.menuForm.sort"
                controls-position="right"
                placeholder="请输入优先级"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="是否显示" prop="hidden">
              <el-radio-group v-model="state.menuForm.hidden">
                <el-radio border :value="0">显示</el-radio>
                <el-radio border :value="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="菜单状态" prop="status">
              <el-radio-group v-model="state.menuForm.status">
                <el-radio border :value="0">启用</el-radio>
                <el-radio border :value="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="16">
            <el-form-item label="菜单描述" prop="description">
              <el-input type="textarea" v-model="state.menuForm.description" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="state.showEdit = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
